package zb.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * 令牌桶限流过滤器
 */
@Component
public class RouterFilter extends ZuulFilter {
    //定义一个令牌桶，每秒产生两个令牌，即每秒最多处理1 个请求
    private static final RateLimiter RATE_LIMITER=RateLimiter.create(1);
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("令牌桶过滤");
        RequestContext currentContext = RequestContext.getCurrentContext();
        //判断有没有令牌
        if(!RATE_LIMITER.tryAcquire()){
            //阻止路由
            currentContext.setSendZuulResponse(false);
            //返回给客户端的信息
            currentContext.setResponseStatusCode(429);
            currentContext.setResponseBody("{'msg':'limit'}");
            return "no";
        }
        return "next";
    }
}
